<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="120px">
      <el-form-item label="banner名称" prop="name">
        <el-input v-model="dataForm.name" placeholder="名称"></el-input>
      </el-form-item>
      <el-form-item label="所属贷超" prop="marketId">
        <el-select v-model="dataForm.marketId" placeholder="所属贷超">
          <el-option v-for="market in marketList" :key="market.id" :label="market.name" :value="market.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item v-model="dataForm.src" label="banner图片" prop="src">
        <el-upload
          class="avatar-uploader"
          :action="url"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload">
          <img v-if="imageUrl" :src="imageUrl" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="链接" prop="url">
        <el-input v-model="dataForm.url" placeholder="链接"></el-input>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="dataForm.status" placeholder="状态">
          <el-option :key="1" :label="'上线'" :value="1"></el-option>
          <el-option :key="2" :label="'下线'" :value="2"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 140px;
    height: 80px;
    line-height: 80px;
    text-align: center;
  }
  .avatar {
    width: 140px;
    height: 80px;
    display: block;
  }
</style>

<script>
  export default {
    data () {
      return {
        visible: false,
        marketList: [],
        dataForm: {
          id: 0,
          name: '',
          src: '',
          url: '',
          status: '',
          marketId: '',
          imageUrl: '',
          marketList: []
        },
        dataRule: {
          name: [
            { required: true, message: '名称不能为空', trigger: 'blur' }
          ],
          marketId: [
            { required: true, message: '所属超市不能为空', trigger: 'blur'}
          ],
          src: [
            { required: true, message: '图片logo不能为空', trigger: 'blur'}
          ],
          url: [
            { required: true, message: '链接不能为空', trigger: 'blur'}
          ],
          status: [
            { required: true, message: '状态不能为空', trigger: 'blur'}
          ]
        }
      }
    },
    methods: {
      handleAvatarSuccess (res, file) {
        this.imageUrl = res.url
        this.dataForm.src = res.url
      },
      beforeAvatarUpload (file) {
        const isJPG = file.type === 'image/jpeg'||'image/png'
        const isLt2M = file.size / 1024 / 1024 < 2

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!')
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!')
        }
        return isJPG && isLt2M
      },
      init (id) {
        this.dataForm.id = id || 0
        this.url = this.$http.adornUrl(`/sys/oss/upload?token=${this.$cookie.get('token')}`)
        this.imageUrl = ''
        this.$http({
          url: this.$http.adornUrl('/api/market/select'),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({data}) => {
          this.marketList = data && data.code === 0 ? data.list : []
        }).then(() => {
          this.visible = true
          this.$nextTick(() => {
            this.$refs['dataForm'].resetFields()
          })
        }).then(() => {
          if (this.dataForm.id) {
            this.$http({
              url: this.$http.adornUrl(`/api/banner/info/${this.dataForm.id}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.dataForm.name = data.banner.name
                this.dataForm.status = data.banner.status
                this.dataForm.alias = data.banner.alias
                this.dataForm.source = data.banner.source
                this.dataForm.url = data.banner.url
                this.dataForm.marketId = data.banner.marketId
                this.dataForm.src = data.banner.src
                this.imageUrl = data.banner.src
              }
            })
          }
        })
      },
      // 表单提交
      dataFormSubmit () {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.$http({
              url: this.$http.adornUrl(`/api/banner/${!this.dataForm.id ? 'save' : 'update'}`),
              method: 'post',
              data: this.$http.adornData({
                'id': this.dataForm.id || undefined,
                'name': this.dataForm.name,
                'url': this.dataForm.url,
                'src': this.dataForm.src,
                'status': this.dataForm.status,
                'marketId': this.dataForm.marketId,
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      }
    }
  }
</script>
